﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using NHibernate.Criterion;
using Project.Common;
using Project.Model;
using System.Xml;

namespace Web
{
	/// <summary>
	/// 功能：分页列表页面
	///       (UserManager)
	/// 作者：luky
	/// 日期：2010-12-22
	/// </summary>
    public partial class UserManager_List : AdminPage
    {
        //创建查询器
        IList<ICriterion> queryList = new List<ICriterion>();
        // 排序字段
        IList<Order> orderList = new List<Order>();

        /// <summary>
        /// 审核状态
        /// </summary>
        protected string sh { get { return base.QueryString("sh"); } }
        /// <summary>
        /// 用户类型
        /// </summary>
        protected string type { get { return base.QueryString("type"); } }
        /// <summary>
        /// 单位
        /// </summary>
        protected string company { get { return base.QueryString("company"); } }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                base.BindEnum2WebControls(UserTypeDropDownList, typeof(EnumUserType), true, 0);
                UserTypeDropDownList.Items.Insert(0,new ListItem("全部",""));
                base.BindEnum2WebControls(SHDropDownList, typeof(EnumIsAudit), true, 0);
                SHDropDownList.Items.Insert(0, new ListItem("全部", ""));

                if (!string.IsNullOrEmpty(company))
                    txt_Company.Text = company;

                this.QuerySelect();
            }
        }
        #region 搜索

        protected void searchButton_Click(object sender, EventArgs e)
        {
            this.QuerySelect();
        }

        private void QuerySelect()
        {
            if (UserTypeDropDownList.Items.FindByValue(type) != null)
                UserTypeDropDownList.Items.FindByValue(type).Selected = true;
            if (SHDropDownList.Items.FindByValue(sh) != null)
                SHDropDownList.Items.FindByValue(sh).Selected = true;

            // 传入条件
            // 添加自定义条件
            if (!string.IsNullOrEmpty(txt_USERNAME.Text))
                queryList.Add(Restrictions.Like(PropertyNameHelper.Resolve<UserManager>(d => d.USERNAME), txt_USERNAME.Text.Trim(), MatchMode.Anywhere));
            if (!string.IsNullOrEmpty(txt_Lxr_name.Text))
                queryList.Add(Restrictions.Like(PropertyNameHelper.Resolve<UserManager>(d => d.Lxrname), txt_Lxr_name.Text.Trim(), MatchMode.Anywhere));
            if (!string.IsNullOrEmpty(txt_Company.Text))
                queryList.Add(Restrictions.Like(PropertyNameHelper.Resolve<UserManager>(d => d.Company), txt_Company.Text.Trim(), MatchMode.Anywhere));
            if (!string.IsNullOrEmpty(txt_Szaddress.Text))
                queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Szaddress), txt_Szaddress.Text.Trim()));
            if (!string.IsNullOrEmpty(txt_Xaddress.Text))
                queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Xaddress), txt_Xaddress.Text.Trim()));
            if (!string.IsNullOrEmpty(sh) && Validator.IsInt(sh))
            {
                if (int.Parse(sh) == 0)
                    queryList.Add(Restrictions.Or(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Sh), sh)
                        , Restrictions.IsNull(PropertyNameHelper.Resolve<UserManager>(d => d.Sh))
                        ));
                else
                    queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Sh),sh));
            }
            if (!string.IsNullOrEmpty(type) && Validator.IsInt(type) && Enum.IsDefined(typeof(EnumUserType), int.Parse(type)))
                queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.UserType), type));

            this.BindGrid();
        }

        #endregion

        private void BindGrid()
        {
            AspNetPager1.RecordCount = ManagerFactory.UserManagerManager.GetCount(queryList);
            IList<UserManager> list = ManagerFactory.UserManagerManager.GetPageList(AspNetPager1, queryList, orderList);
            GridView1.DataSource = list;
            GridView1.DataBind();
        }

        #region gridview绑定及命令事件

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            { 
                object itemId = e.CommandArgument;
                if (e.CommandName == "DeleteIt")
                {
                    #region 约束检查
                    bool IsExistFK = false;
                    UserManager model = ManagerFactory.UserManagerManager.Get(int.Parse(itemId.ToString()));
                    IList<ICriterion> queryList1 = new List<ICriterion>();
                    queryList1.Add(Restrictions.Eq(PropertyNameHelper.Resolve<Indexbasictable>(d => d.USERNAME), model.USERNAME));

                    IList<ICriterion> queryList2 = new List<ICriterion>();
                    queryList2.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Id),int.Parse(itemId.ToString())));
                    queryList2.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.UserType),"7"));
                    queryList2.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.Sh), "0"));
                    bool userType = ManagerFactory.UserManagerManager.GetCount(queryList2) > 0;

                    IsExistFK = ManagerFactory.IndexbasictableManager.GetCount(queryList1) > 0;
                    #endregion
                    if (!IsExistFK && userType && Validator.IsInt(itemId.ToString()))
                    {
                        if (currentUser.UserType == ((int)EnumUserType.管理员).ToString())
                        {
                            ManagerFactory.UserManagerManager.Delete(int.Parse(itemId.ToString()));

                            this.QuerySelect();
                        }
                        else
                            Alert("权限不足！");
                    }
                    else
                    {
                        ExecJsAjax("alert('该记录已经被使用,不能删除！');", Page);
                    }
                }
                else if (e.CommandName == "AuditIt")
                {
                    if (Validator.IsInt(itemId.ToString()))
                    {
                        UserManager model = ManagerFactory.UserManagerManager.Get(int.Parse(itemId.ToString()));
                        if (model != null)
                        {   
                            // 赋值
                            model.Sh = !string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString() ? ((int)EnumIsAudit.未审核).ToString() : ((int)EnumIsAudit.已审核).ToString();
                            // 更新
                            ManagerFactory.UserManagerManager.Update(model);

                            // 审核成功 向用户发送短信:包含用户名和密码
                            // 获取用户手机号
                            if (model.Sh == ((int)EnumIsAudit.已审核).ToString() && base.IsSendSMS)
                            {
                                if (!Validator.IsMobile(model.Lxrtel))
                                {
                                    Alert("'联系人手机'填写的不是有效的手机号码,短信发送失败!");
                                }
                                else
                                {
                                    string content = "青海科技计划项目受理中心提示:您的帐号 " + model.USERNAME + " 已审核通过.密码是: " + model.UserPass + " 请注意保存.";
                                   // string content = "青海科技计划项目受理中心提示:您的帐号 " + model.USERNAME + " 已审核通过.密码是: " + model.UserPass + " 请注意保存.";
                                    //SendSMS(model.Lxrtel, content);
                                    XmlDocument doc = new XmlDocument();
                                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                                    doc.AppendChild(dec);
                                    //创建一个根节点（一级）
                                    XmlElement root = doc.CreateElement("root");
                                    doc.AppendChild(root);

                                    XmlElement element = doc.CreateElement("authkeycode");
                                    element.InnerText = "cWhreGpzeHh6anMzOWI3ZTM5YWY4ZGM3ZDJhNTI4ZTRhMDlhZThjNDE0ZA==";
                                    root.AppendChild(element);
                                    XmlElement element2 = doc.CreateElement("phsnumber");
                                    element2.InnerText = model.Lxrtel;
                                    root.AppendChild(element2);
                                    XmlElement element3 = doc.CreateElement("smscontent");
                                    element3.InnerText = content;
                                    root.AppendChild(element3);
                                    string resqult = doc.OuterXml;
                                    //Console.Write(resqult);
                                    //  doc.Save(Server.MapPath("data1.xml"));
                                    // ServiceReference service = new ServiceReference(webservice);
                                    WebReference.SmsInterfacesService SMS = new WebReference.SmsInterfacesService();
                                    SMS.smsdata(resqult);
                                    Alert("短信发送成功!");
                                }
                            }

                            this.QuerySelect();
                        }
                        else
                        {
                            ExecJsAjax("alert('记录不存在,不能操作！');", Page);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                ExecJsAjax("alert('发生错误:" + ex.Message.Replace("/r/n","") + "！');", Page);
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //e.Row.Attributes.Add("onmouseout", "this.className=this.className.replace(new RegExp(\"( ?|^)gridSelectedItem\\\\b\"),\"\");");
                //e.Row.Attributes.Add("onmouseover", "this.className+='" + " gridSelectedItem" + "'");
            }
        }

        #endregion

        #region 分页

        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            this.QuerySelect();
        }

        #endregion

        #region 排序

        public string SortD
        {
            get
            {
                if (ViewState["SortD"] == null)
                {
                    switch (GridView1.SortDirection)
                    {
                        case SortDirection.Ascending:
                            ViewState["SortD"] = "ASC";
                            break;
                        case SortDirection.Descending:
                            ViewState["SortD"] = "DESC";
                            break;
                    }
                }
                return Convert.ToString(ViewState["SortD"]);
            }
            set
            {
                ViewState["SortD"] = value;
            }
        }
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortD = (SortD.ToLower() == "asc" ? "DESC" : "ASC");
            orderList.Add(new Order(e.SortExpression,SortD.ToLower()=="ASC".ToLower()));
        }
        protected void GridView1_Sorted(object sender, EventArgs e)
        {
            this.QuerySelect();
        }
       
        #endregion

        protected void UserTypeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Response.Redirect("list.aspx?type="+UserTypeDropDownList.SelectedValue);
            //Response.Redirect(WebHelper.BuildUrl(Request.Url.ToString(), "type", UserTypeDropDownList.SelectedValue));
            Response.Redirect(WebHelper.BuildUrl(Request.Url.ToString(), new string[] { "type", "company" }, new string[] { UserTypeDropDownList.SelectedValue, txt_Company.Text }));
        }

        protected void SHDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Response.Redirect("list.aspx?sh="+SHDropDownList.SelectedValue);
            Response.Redirect(WebHelper.BuildUrl(Request.Url.ToString(), new string[] { "sh", "company" }, new string[] { SHDropDownList.SelectedValue,txt_Company.Text }));
        }

    }
}
